<template>
  <div class="ele-body">
    <el-card shadow="never">
      <!-- 搜索表单 -->
      <el-form :model="where" label-width="77px" class="ele-form-search" @keyup.enter.native="reload"
        @submit.native.prevent>
        <slot name="search">
          <!-- 默认搜索内容（可由父组件插槽替换） -->
          <el-row :gutter="15">
            <el-col :lg="6" :md="12">
              <el-form-item label="关键词">
                <el-input clearable v-model="where.keyword" placeholder="请输入关键词" />
              </el-form-item>
            </el-col>
            <el-col :lg="6" :md="12">
              <div class="ele-form-actions">
                <el-button type="primary" icon="el-icon-search" class="ele-btn-icon" @click="reload">查询</el-button>
                <el-button @click="reset">重置</el-button>
              </div>
            </el-col>
          </el-row>
        </slot>
      </el-form>

      <!-- 数据表格 -->
      <ele-pro-table ref="table" :where="where" :datasource="url" :columns="columns" :selection.sync="selection"
        height="calc(100vh - 315px)">

        <!-- 表头工具栏 -->
        <template slot="toolbar">
          <el-button size="small" type="primary" icon="el-icon-plus" class="ele-btn-icon" @click="openEdit(null)"
            v-if="hasPerm(':add')">添加</el-button>

          <el-button size="small" type="danger" icon="el-icon-delete" class="ele-btn-icon" @click="removeBatch"
            v-if="hasPerm(':dall')">删除</el-button>

          <el-button @click="showImport = true" icon="el-icon-upload2" class="ele-btn-icon" size="small"
            v-if="importEnabled">导入</el-button>

          <el-button size="small" type="success" icon="el-icon-download" class="ele-btn-icon" @click="exportExcel"
            v-if="hasPerm(':export')">导出</el-button>
        </template>

        <!-- 操作列 -->
        <template slot="action" slot-scope="{row}">
          <el-link type="primary" :underline="false" icon="el-icon-edit" @click="openEdit(row)"
            v-if="hasPerm(':edit')">修改</el-link>

          <el-popconfirm class="ele-action" title="确定要删除此项？" @confirm="remove(row)">
            <el-link type="danger" slot="reference" :underline="false" icon="el-icon-delete"
              v-if="hasPerm(':delete')">删除</el-link>
          </el-popconfirm>
        </template>

        <!-- 状态列插槽支持 -->
        <template v-if="$scopedSlots.status" v-slot:status="scope">
          <slot name="status" v-bind="scope" />
        </template>
      </ele-pro-table>
    </el-card>

    <!-- 编辑弹窗 -->
    <component :is="editComponent" :data="current" :visible.sync="showEdit" @done="reload" />

    <!-- 导入弹窗 -->
    <ImportDialog v-if="importEnabled" :visible.sync="showImport" :title="importTitle" :upload-url="importUrl"
      :template-url="importTemplateUrl" @done="onImportDone" />


  </div>
</template>

<script>
  import {
    mapGetters
  } from 'vuex';
  import ImportDialog from '@/components/ImportDialog.vue';

  export default {
    name: 'CommonTable',
    components: { ImportDialog },
    props: {
      permFix: {
        type: String,
        required: true
      }, // 权限前缀
      url: {
        type: String,
        required: true
      }, // 数据请求地址
      columns: {
        type: Array,
        required: true
      }, // 表格列配置
      editComponent: {
        type: [Object, Function],
        required: true
      }, // 编辑弹窗组件
      importEnabled: {
        type: Boolean,
        default: false
      },

      importTitle: {
        type: String,
        default: '导入数据'
      },
      importUrl: String,
      importTemplateUrl: String
    },
    computed: {
      ...mapGetters(['permission'])
    },
    data() {
      return {
        where: {},
        selection: [],
        current: null,
        showEdit: false,
        showImport: false,
      }
    },
    methods: {
      hasPerm(suffix) {
        console.log('--------------suffix-------------',suffix);
        return this.permission.includes(this.permFix + suffix);
      },
      reload() {
        this.$refs.table.reload({
          where: this.where
        });
      },
      reset() {
        this.where = {};
        this.reload();
      },
      openEdit(row) {
        this.current = row;
        this.showEdit = true;
      },
      remove(row) {
        const loading = this.$loading({
          lock: true
        });
        this.$http.post(`${this.url.replace('/index', '/delete')}`, {
          id: row.id
        }).then(res => {
          loading.close();
          if (res.data.code === 0) {
            this.$message.success(res.data.msg);
            this.reload();
          } else {
            this.$message.error(res.data.msg);
          }
        }).catch(e => {
          loading.close();
          this.$message.error(e.message);
        });
      },
      removeBatch() {
        if (!this.selection.length) {
          this.$message.error('请至少选择一条数据');
          return;
        }
        this.$confirm('确定要删除选中的项吗?', '提示', {
          type: 'warning'
        }).then(() => {
          const loading = this.$loading({
            lock: true
          });
          this.$http.post(`${this.url.replace('/index', '/delete')}`, {
            id: this.selection.map(d => d.id)
          }).then(res => {
            loading.close();
            if (res.data.code === 0) {
              this.$message.success(res.data.msg);
              this.reload();
            } else {
              this.$message.error(res.data.msg);
            }
          }).catch(e => {
            loading.close();
            this.$message.error(e.message);
          });
        });
      },
      exportExcel() {
        let info = JSON.parse(JSON.stringify(this.where));
        this.$http.get(`${this.url.replace('/index', '/exportExcel')}`, info).then(res => {
          let data = res.data;
          if (data.code === 0) {
            window.location.href = data.data;
            this.$message.success('导出成功');
          } else {
            this.$message.error('导出失败');
          }
        });
      }
    }
  }
</script>

<style scoped>
</style>
